package logic

import (
	"context"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"order/model"
	"order/order"
	"order/utils"

	"order/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type OrderListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewOrderListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *OrderListLogic {
	return &OrderListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}
func check(in *order.OrderListRequest) error {
	if in.UserId == 0 {
		return status.Error(codes.InvalidArgument, "user_id is required")
	}
	return nil
}
func (l *OrderListLogic) OrderList(in *order.OrderListRequest) (*order.OrderListResponse, error) {
	if in.UserId == 0 {
		return nil, status.Error(codes.InvalidArgument, "user_id is required")
	}

	var ids []int
	if err := model.Db.Model(&model.Order{}).Select("id").Where("user_id = ?", in.UserId).Find(&ids).Error; err != nil {
		return nil, err
	}

	var total int64
	model.Db.Model(&model.OrderGoods{}).Count(&total)

	var orderGoodsModels []model.OrderGoods
	offset := (in.Page - 1) * in.Limit
	if in.LogisticsStatus >= 1 && in.LogisticsStatus <= 5 {
		model.Db.Model(&model.OrderGoods{}).Where("order_id in ?", ids).Where("logistics_status = ?", in.LogisticsStatus).Offset(int(offset)).Limit(int(in.Limit)).Order("id desc").Find(&orderGoodsModels)
	} else {
		model.Db.Model(&model.OrderGoods{}).Where("order_id in ?", ids).Offset(int(offset)).Limit(int(in.Limit)).Order("id desc").Find(&orderGoodsModels)
	}

	var orderGoodsDatas []*order.OrderGoodsData
	for _, v := range orderGoodsModels {
		orderGoodsData := utils.OrderGoodsModelToProto(v)
		orderGoodsDatas = append(orderGoodsDatas, orderGoodsData)
	}

	return &order.OrderListResponse{
		OrderGoodsDatas: orderGoodsDatas,
		Total:           int32(total),
	}, nil
}
